package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.POJO.Setmeal;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.SetMealService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Transactional
@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private JedisPool jedisPool;
    @Value("${out_put_path}")
    private String outputpath;

    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> result = setMealDao.findPage(queryString);
        return new PageResult(result.getTotal(), result.getResult());
    }


    public void add(Setmeal setmeal, Integer[] checkGroupIds) {
        //首先对套餐的基本信息进行添加
        setMealDao.add(setmeal);

        if (checkGroupIds != null && checkGroupIds.length > 0) {
            //遍历checkGroupIds
            for (Integer checkGroupId : checkGroupIds) {
                //对中间进行套餐和检查组之间的关联
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmeal.getId());
                map.put("checkgroup_id", checkGroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
        //将图片名称保存到Redis
        //jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }


    //生成静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.getSetmeal();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐详情页面(多个)
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
            for(Setmeal setmeal : setmealList){
                Map<String,Object> dataMap = new HashMap<String,Object>();
                dataMap.put("setmeal",setMealDao.listById(setmeal.getId()));
                this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",dataMap);
            }
    }

    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }


    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try{
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File docFile = new File(outputpath + "\\" +htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出文件
            template.process(dataMap,out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(null != out){
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void delete(Integer id) {
        //判断该套餐在t_order中是否存在，若存在则不允许删除
        Long count = setMealDao.countSetmealInOrder(id);
        if (count > 0) {
            //已被包含，无法删除
            throw new RuntimeException("当前套餐被引用，不能删");
        } else {
            //清除该套餐再中间表中的关联关系
            setMealDao.deleteCheckGroupBySetMealId(id);
            //清除基本信息
            setMealDao.delete(id);
        }
    }

    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    public List<Integer> findCheckGroupAndCheckItemById(Integer id) {
        return setMealDao.findCheckGroupAndCheckItemById(id);
    }


    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        //首先对基本信息进行更新
        setMealDao.edit(setmeal);
        //清除该套餐再中间表中的关联关系
        setMealDao.deleteCheckGroupBySetMealId(setmeal.getId());
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            //遍历checkGroupIds
            for (Integer checkGroupId : checkGroupIds) {
                //对中间进行套餐和检查组之间的关联
                Map<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", setmeal.getId());
                map.put("checkgroup_id", checkGroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }

    public List<Setmeal> getSetmeal() {
        return setMealDao.findAll();
    }


    public Setmeal listById(Integer id) {
        return setMealDao.listById(id);
    }


    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }
}
